//
//  XPEmojiTool.swift
//  SinaWeibo
//
//  Created by 徐攀 on 16/5/21.
//  Copyright © 2016年 徐攀. All rights reserved.
//

import UIKit

class XPEmojiTool: NSObject {
    
    static let sharedTool: XPEmojiTool = XPEmojiTool()
    
    private override init() {
        super.init()
    }
    
    private lazy var bundle: NSBundle = {
        let bundlePath = NSBundle.mainBundle().pathForResource("Emoticons.bundle", ofType: nil)!
        let bundle = NSBundle(path: bundlePath)!
        return bundle
    }()
    
    // MARK: - 最底层数组
    private lazy var defaultEmoticons: [XPEmoticon] = {
         return self.emoticonAtPath("default/info.plist")
    }()
    private lazy var EmojiEmoticons: [XPEmoticon] = {
        return self.emoticonAtPath("emoji/info.plist")
    }()
    private lazy var lxhEmoticons: [XPEmoticon] = {
        return self.emoticonAtPath("lxh/info.plist")
    }()
    
    // 最外层数组模型
    lazy var emoticonCollection: [[[XPEmoticon]]] = {
        return [
            self.emoticonsForSection(self.defaultEmoticons),
            self.emoticonsForSection(self.EmojiEmoticons),
            self.emoticonsForSection(self.lxhEmoticons),
        ]
    }()
    
    // MARK: - 获取第二级数组（即将底层的数组截取为几个小数组）
    private func emoticonsForSection(emoticons: [XPEmoticon]) ->[[XPEmoticon]] {
        let pagesNum = (emoticons.count - 1) / 20 + 1
        
        var pagesArr: [[XPEmoticon]] = [[XPEmoticon]]()
        
        for i in 0..<pagesNum {
            let loc = 20 * i
            var len = 20
            
            if i == pagesNum - 1 {
               len = emoticons.count - loc
            }
            
            let range = NSMakeRange(loc, len)
            let rangeArr = (emoticons as NSArray).subarrayWithRange(range) as! [XPEmoticon]
            pagesArr.append(rangeArr)
        }
       return pagesArr
    }
    
    private func emoticonAtPath(path: String) ->[XPEmoticon] {
        // 根据传入的bundle路径获取到plist路径
        let emoticonPath = bundle.pathForResource(path, ofType: nil)!
        
        let emoticons = NSArray(contentsOfFile: emoticonPath)!
        
        var tempArray = [XPEmoticon]()
        
        for dict in emoticons {
            let emoticonM = XPEmoticon(dict: (dict as! [String: AnyObject]))
            
            let oldPath = bundle.pathForResource(path, ofType: nil)! as NSString
            // 必须得判断它是否是Emoji表情，因为Emoji里面没有png
            if emoticonM.type == "0" {
                let newPath = (oldPath.stringByDeletingLastPathComponent as NSString).stringByAppendingPathComponent(emoticonM.png!)
                emoticonM.iconName = newPath
            }
            
            tempArray.append(emoticonM)
        }
        
        return tempArray
    }

}
